package com.learn.egmvc4.base.exception;

import com.learn.egmvc4.base.response.JsonResult;
import com.learn.egmvc4.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException e){
        log.error("IllegalArgumentException:{}", e.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandlerBindException(BindException e){
        String data = e.getFieldError().getDefaultMessage();
        log.error("BindException:{}", data);
        return new JsonResult(StatusCode.VALIDATION_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException e){
        String data = e.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:{}", data);
        return new JsonResult(StatusCode.VALIDATION_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException e){
        log.error("RuntimeException:{}", e.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandler(Throwable ex){
        log.error("Throwable:{}", ex.getMessage());
        return new JsonResult(StatusCode.THROWABLE_ERROR,ex.getMessage());
    }
}
